import 'dart:async';

import 'package:flutter_deer/database/beans/get_user_info_entity.dart';
import 'package:flutter_deer/database/beans/mqtt_msg_model.dart';
import 'package:flutter_deer/database/database_manager.dart';
import 'package:flutter_deer/dl/dl.dart';
import 'package:flutter_deer/mvvm/base_net_provider.dart';
import 'package:flutter_deer/net/dio_utils.dart';
import 'package:flutter_deer/net/http_api.dart';
import 'package:flutter_deer/objectbox.g.dart';
import 'package:flutter_deer/res/constant.dart';
import 'package:flutter_deer/util/mqtt_manager.dart';
import 'package:sp_util/sp_util.dart';

import 'mqtt_handler.dart';

class MqttProvider extends BaseNetProvider implements MqttCallback {
  MqttManager manager = MqttManager();
  bool isConnect = false;
  late Store store;
  late Box<MqttMsgModel> mqttMsgModelBox;
  final mqttHandler = MqttHandler();

  // init
  Future<void> initMqtt() async {
    manager.initMqtt(callback: this);

    store = getIt<ObjectIdBox>().store;
    mqttMsgModelBox = store.box<MqttMsgModel>();

    startPollingCycle();
  }

  @override
  void onConnect(bool isSuccess) {
    isConnect = isSuccess;
  }

  @override
  void onMessageReceived(MqttMsgModel message, String tag) {
    print('[mqtt-$tag] ---> onMessageReceived: $message');
    try {
      // 插入前检查是否已存在
      final exists = mqttMsgModelBox.query(MqttMsgModel_.msgId.equals(message.msgId)).build().findFirst();
      if (exists == null) {
        mqttMsgModelBox.put(message);
        mqttHandler.onConsume(message);
      }
    } catch (e, stackTrace) {
      print('[mqtt-$tag] ---> 消息处理异常: $e');
      print('[mqtt-$tag] ---> 错误堆栈: $stackTrace');
    }
  }

  // 停止轮询
  void stopPolling() {
    _pollingTimer?.cancel();
  }

  @override
  void dispose() {
    stopPollingCycle();
    super.dispose();
  }

  // 接口请求消息
  void requestMsg() {
    asyncRequestNetwork<String>(Method.get, url: HttpApi.mqttPull, isShow: false, queryParameters: {
      'deviceSn': SpUtil.getString(Constant.snCode),
      'mchCode': GetUserInfoEntity.get()?.loginMerchantCode,
      'userId': GetUserInfoEntity.get()?.id,
    }, onSuccess: (data) {
      _scheduleNextPolling();
      if (data == null || data.isEmpty) {
        return;
      }
      try {
        final item = parseData(data);
        for (int i = 0; i < item.length; i++) {
          final item2 = item[i].trim();
          // print('forEach--->[$i]--->[${item2}]');
          if (item2.isNotEmpty) {
            try {
              manager.parseData(item2, tag: 'http');
            } catch (e, s) {
              print('[mqtt-http] ---> manager.parseData 异常: $e\n$s');
            }
          }
        }
      } catch (e, s) {
        print('[mqtt-http] ---> 解析消息失败: $e\n$s');
      }
    }, onError: (code, msg) {
      _scheduleNextPolling();
      print('[mqtt-http] requestMsg onError: $code $msg');
    });
  }

  // 写个方法：解析成数组List<String>。数据格式：[asdasdasd,asdasdasd]
  List<String> parseData(String data) {
    if (data == null || data.isEmpty) {
      return [];
    }
    try {
      if (data.startsWith('[') && data.endsWith(']')) {
        data = data.substring(1, data.length - 1);
      }
      return data.split(',').map((e) => e.trim()).where((e) => e.isNotEmpty).toList();
    } catch (e) {
      print('[mqtt] ---> parseData 解析失败: $e');
      return [];
    }
  }

  // --------轮询Mqtt消息--------
  Timer? _pollingTimer;
  bool _isPollingRunning = false;

  // 开启循环
  void startPollingCycle() {
    if (_isPollingRunning) return;
    _isPollingRunning = true;
    _scheduleNextPolling();
  }

  // 停止循环
  void stopPollingCycle() {
    _pollingTimer?.cancel();
    _isPollingRunning = false;
  }

  // 循环任务
  void _scheduleNextPolling() {
    int sec = 5;
    if (manager.isConnected) {
      sec = 60;
    } else {
      sec = 5;
    }
    _pollingTimer?.cancel();
    _pollingTimer = Timer(Duration(seconds: sec), () {
      if (!manager.isConnected) {
        requestMsg();
      }
    });
  }
}
